import { createRouter, createWebHashHistory } from 'vue-router'
// import HomeView from '../views/home/HomeView.vue'
// import LoginView from '../views/login/LoginView.vue'
// import RegisterView from '../views/register/RegisterView.vue'
// import ShopView from '../views/shop/ShopView.vue'
// to 跳到哪里去
// from 从哪里跳过来
// next 继续执行
const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/home/HomeView')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/user/UserView')
  },
  {
    path: '/cart-list',
    name: 'cart',
    component: () => import('../views/cart/CartView')
  },
  {
    path: '/shop/:id',
    name: 'shop',
    component: () => import('../views/shop/ShopView')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/register/RegisterView'),
    beforeEnter: (to, from, next) => {
      if (localStorage.isLogin === 'true') {
        next({ name: 'home' })
      } else {
        next()
      }
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/LoginView'),
    // 访问login页面之前执行
    beforeEnter: (to, from, next) => {
      if (localStorage.isLogin === 'true') {
        next({ name: 'home' })
      } else {
        next()
      }
    }
  },
  {
    path: '/order-confirmation/:shopId',
    name: 'orderConfirmation',
    component: () => import('../views/order/OrderConfirmation')
  },
  {
    path: '/order-list',
    name: 'orderList',
    component: () => import('../views/order/OrderList')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  if (localStorage.isLogin === 'true' || to.name === 'login' || to.name === 'register') {
    next()
  } else {
    next({ name: 'login' })
  }
})

export default router
